<?php

namespace app\home\controller;

use think\Controller;
use think\Request;

class Cart extends Base
{
    public function addcart(){
        # 判断他是不是get请求，如果是get请求那就让他跳转页面
        if(request()->isGet()){
            return view("goods/index");
        }
        # 接收数据
        $params = input();
        # 数据检测
        $validata = $this->validate($params,[
            "goods_id" => "require",
            "goods_spec_id" => "require",
            "number" => "require",
        ]);
        if($validata !== true){
            $this->error($validata);
        }
        # 数据处理
        \app\home\logic\CartLogic::getAddCart($params["goods_id"],$params["goods_spec_id"],$params["number"]);
        $goods = \app\home\logic\CartLogic::getFindgoods($params["goods_id"],$params["goods_spec_id"]);
        # 返回数据
        // dump($goods);die;
        return view("Cart/cart",["goods" => $goods ,"number" => $params['number']]);
    }
    public function index()
    {
        # 查询所有添加到购物车的商品
        $goods_data = \app\home\logic\CartLogic::cartAll();
        foreach ($goods_data as $key => $value) {
            $goods_data[$key]["goods"] = \app\home\logic\CartLogic::getFindgoods($value["goods_id"],$value["spec_goods_id"]);
        }
        // dump($goods_data);die;
        return view("cart/index",["goods"=>$goods_data]);
    }
    public function delcart($id){
        \app\home\logic\CartLogic::delcart($id);
        $res = [
            "status" => 200,
            "msg"    => "删除成功"
        ];
        return json($res);
    }
    public function change_num(){
        $params = input();
        $validate = $this->validate($params,[
            "number" => "require",
        ]);
        if($validate !== true){
            $res = [
                "status" => 401,
                "msg" => $validate
            ];
            return json($res);
        }
        \app\home\logic\CartLogic::updataNumber($params["id"],$params["number"]);
        $res = [
            "status" => 200,
            "msg"   => "修改成功"
        ];
        return json($res);
    }
    public function changeStatus(){
        $params = input();
        $validate = $this->validate($params,[
            "is_selected" => "require"
        ]);
        if($validate !== true){
            $res = [
                "status" => 401,
                "msg"   => $validate
            ];
            return json($res);
        }
        \app\home\logic\CartLogic::changeStatus($params["id"],$params["is_selected"]);
        $res = [
            "status" => 200,
            "msg"  => "修改成功"
        ];
        return json($res);
    }
}
